package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.utils.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.exception.CustomException;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.mess.ArticleVisitStreamMess;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.constants.ArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.utils.common.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author rookie001
 * @creat 2023-06-05-13:59
 */
@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private ArticleFreemarkerService articleFreemarkerService;

    //app查看功能

    public ResponseResult load(Short type, ArticleHomeDto dto) {
        //数据校验
        if (type == null && dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //数据处理
        //判断分页
        Integer size = dto.getSize();
        if (size == 0 || size == null) {
            size = 10;
        }
        size = Math.min(size, 50);
        dto.setSize(size);
        //判断频道
        if (StringUtils.isEmpty(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //判断时间
        Date min = dto.getMinBehotTime();
        Date max = dto.getMaxBehotTime();
        if (min == null) dto.setMinBehotTime(new Date());
        if (max == null) dto.setMaxBehotTime(new Date());
        //判断type
        if (!type.equals(ArticleConstants.LOADTYPE_LOAD_MORE) &&
                !type.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            type = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //业务操作
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, type);
        //返回结果
        return ResponseResult.okResult(apArticles);
    }

    //自媒体保存或修改文章 同步更新app
    @Override
    public ResponseResult saveArticle(ArticleDto dto) {
        //数据校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //讲dto赋值到实体类
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);
        //判断文章id 是否为空
        if (dto.getId() == null) {
            //空 为保存ap_article
            save(apArticle);
            //保存ap_a_config
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);
            //保存ap_a_content
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(dto.getAuthorId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);
        } else {
            //否则 修改
            //修改 文章
            updateById(apArticle);
            //修改文章内容
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, dto.getId()));
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.updateById(apArticleContent);
        }
        //异步调用 生成静态文件上传minio app端显示修改或生成
        articleFreemarkerService.buildArticleToMinIO(apArticle, dto.getContent());
        //结果返回
        return ResponseResult.okResult(apArticle.getId());
    }

    @Autowired
    private RedisTemplate redisTemplate;

    //加载文章数据回显
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        //数据校验
        if (dto == null || dto.getArticleId() == 0 || dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取用户id 判断是否登录
        Integer id = AppThreadLocalUtils.getUser().getId();
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.TOKEN_EXPIRE);
        }
        boolean like = false;
        boolean unlike = false;
        boolean User = false;
        boolean collection = false;
        //获取key
        String keyLike = id + dto.getArticleId() + "getUser";
        String keyUser = id + dto.getArticleId() + dto.getAuthorId() + "userlike";
        String keyUnlike = id + dto.getArticleId() + "unlike";
        String keycollection = id + dto.getArticleId() + "collection";
        //判断点赞 不喜欢 关注 收藏
        if (redisTemplate.opsForValue().get(keyLike) != null) like = true;
        if (redisTemplate.opsForValue().get(keyUser) != null) User = true;
        if (redisTemplate.opsForValue().get(keyUnlike) != null) unlike = true;
        if (redisTemplate.opsForValue().get(keycollection) != null) collection = true;

        //装入集合
        Map<String, Object> map = new HashMap<>();
        map.put("islike", like);
        map.put("islunlike", unlike);
        map.put("iscollection", collection);
        map.put("isfollow", User);
        return ResponseResult.okResult(map);
    }


    //管理端修改同步更新app端频道
    @Override
    public void updateChannel(WmChannel wmChannel) {
        //数据校验
        if (wmChannel==null){
            return ;
        }
        //根据频道id获取
        List<ApArticle> list = list(Wrappers.<ApArticle>lambdaQuery().eq(ApArticle::getChannelId, wmChannel.getId()));
        if (!list.isEmpty()) {
            for (ApArticle apArticle : list) {
                apArticle.setChannelName(wmChannel.getName());
                updateById(apArticle);
            }
        }
    }
    @Autowired
    private CacheService cacheService;
    //加载文章 先从redis获取 再去DB中load
    @Override
    public ResponseResult loadFirstPage(Short type, ArticleHomeDto dto) {
        String json = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + type);
        if (StringUtils.isEmpty(json)){
            List<HotArticleVo> hotArticleVos = JSON.parseObject(json, List.class);
            return ResponseResult.okResult(hotArticleVos);
        }else {
           return load(type,dto);
        }
    }



    //更新文章的分值  同时更新缓存中的热点文章数据
    @Override
    public void updateScore(ArticleVisitStreamMess mess) {
        //1.更新文章的阅读、点赞、收藏、评论的数量
        ApArticle apArticle = updateArticle(mess);
        //2.计算文章的分值
        Integer score = computeScore(apArticle);
        score = score * 3;

        //3.替换当前文章对应频道的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());

        //4.替换推荐对应的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);

    }

 /* 替换数据并且存入到redis*/

    private void replaceDataToRedis(ApArticle apArticle, Integer score, String s) {
        String articleListStr = cacheService.get(s);
        if (org.apache.commons.lang.StringUtils.isNotBlank(articleListStr)) {
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(articleListStr, HotArticleVo.class);

            boolean flag = true;

            //如果缓存中存在该文章，只更新分值
            for (HotArticleVo hotArticleVo : hotArticleVoList) {
                if (hotArticleVo.getId().equals(apArticle.getId())) {
                    hotArticleVo.setScore(score);
                    flag = false;
                    break;
                }
            }

            //如果缓存中不存在，查询缓存中分值最小的一条数据，进行分值的比较，如果当前文章的分值大于缓存中的数据，就替换
            if (flag) {
                if (hotArticleVoList.size() >= 30) {
                    hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
                    HotArticleVo lastHot = hotArticleVoList.get(hotArticleVoList.size() - 1);
                    if (lastHot.getScore() < score) {
                        hotArticleVoList.remove(lastHot);
                        HotArticleVo hot = new HotArticleVo();
                        BeanUtils.copyProperties(apArticle, hot);
                        hot.setScore(score);
                        hotArticleVoList.add(hot);
                    }


                } else {
                    HotArticleVo hot = new HotArticleVo();
                    BeanUtils.copyProperties(apArticle, hot);
                    hot.setScore(score);
                    hotArticleVoList.add(hot);
                }
            }
            //缓存到redis
            hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
            cacheService.set(s, JSON.toJSONString(hotArticleVoList));

        }
    }

    /*更新文章行为数量*/
    private ApArticle updateArticle(ArticleVisitStreamMess mess) {
        ApArticle apArticle = getById(mess.getArticleId());
        apArticle.setCollection(apArticle.getCollection()==null? 0:apArticle.getCollection()+mess.getCollect());
        apArticle.setComment(apArticle.getComment()==null?0:apArticle.getComment()+mess.getComment());
        apArticle.setLikes(apArticle.getLikes()==null?0:apArticle.getLikes()+mess.getLike());
        apArticle.setViews(apArticle.getViews()==null?0:apArticle.getViews()+mess.getView());
        updateById(apArticle);
        return apArticle;

    }

     /*计算文章的具体分值*/
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if(apArticle.getLikes() != null){
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(apArticle.getViews() != null){
            score += apArticle.getViews();
        }
        if(apArticle.getComment() != null){
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if(apArticle.getCollection() != null){
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }
}

